<template>
  <div>
    <el-tag
      v-for="tag in tags"
      :key="tag.name"
      closable
      @close="handleClose(tag)"
      :type="tag.type"
      @click="open(tag)"
    >{{tag.name}}</el-tag>
  </div>
</template>
<script>
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      tags: [],
      // 选中的tag
      currentTag: {},
      maxShow: 10,
    };
  },
  methods: {
    ...mapMutations(["setActiveMenu"]),
    /**
     * 打开标签，外部调用方法
     * tag:{
     *  name:标签名称
     *  index：路由
     *  type：打开状态
     * }
     */
    addTag(tag) {
      var flag = false;
      for (var item of this.tags) {
        if (item.index === tag.index) {
          flag = true;
          if (this.currentTag.index != tag.index) {
            item["type"] = "success";
            this.currentTag["type"] = "info";
            this.currentTag = item;
          }
          break;
        }
      }
      if (!flag) {
        if (this.tags.length >= this.maxShow) {
          this.tags.splice(0, 1);
        }
        tag["type"] = "success";
        this.tags.push(tag);
        this.currentTag["type"] = "info";
        this.currentTag = tag;
      }
    },
    /**
     * 点击标签调用事件，路由跳转
     */
    open(tag) {
      this.currentTag["type"] = "info";
      tag["type"] = "success";
      this.currentTag = tag;
      this.$router.push({ path: tag.index, params: { id: "1" } });
      this.setActiveMenu(this.currentTag.index);
    },
    /**
     * 关闭标签调用事件
     */
    handleClose(tag) {
      var tagIndex = this.tags.indexOf(tag);
      debugger;
      // 如果关闭的是当前打开界面
      if (tag === this.currentTag) {
        if (tagIndex === 0) {
          tagIndex = this.tags.length - 1;
        } else {
          tagIndex = tagIndex - 1;
        }
        
      if (tagIndex === 0) {
        // this.$router.push({ path: "/home", params: { id: "1" } });
         this.$router.push('/home')
        this.setActiveMenu("");
      } else {
        this.currentTag = this.tags[tagIndex];
        this.currentTag["type"] = "success";
        this.$router.push({ path: this.currentTag.index, params: { id: "1" } });
        this.setActiveMenu(this.currentTag.index);
      }
      }
      this.tags.splice(this.tags.indexOf(tag), 1);
    },
  },
};
</script>
<style>
</style>